//
//  OAuthViewController.swift
//  WeiBo_Private
//
//  Created by Yangperlove on 16/1/12.
//  Copyright © 2016年 Yangperlove. All rights reserved.
//

import UIKit
import SVProgressHUD
import AFNetworking

class OAuthViewController: UIViewController {
    
    let webView = UIWebView()
    override func loadView() {
        webView.delegate = self
        self.view = webView
        
        
    }

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view.
        //设置导航条
        setupNavBar()
        
        loadOAuthPage()
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    

    func setupNavBar() {
        self.navigationItem.leftBarButtonItem = UIBarButtonItem(title: "关闭", style: .Plain, target: self, action: "closeRegisterPage")
        
        self.navigationItem.rightBarButtonItem = UIBarButtonItem(title: "测试账号", style: .Plain, target: self, action: "saveuserNameAndPasswd")
    }
    
    //测试账号按钮
    func saveuserNameAndPasswd() {
        let js = "document.getElementById('userId').value = '18766969166', document.getElementById('passwd').value = 'yangp97574006'"
        webView.stringByEvaluatingJavaScriptFromString(js)
    }
    
    //关闭按钮
    func closeRegisterPage() {
        dismissViewControllerAnimated(true, completion: nil)
        SVProgressHUD.dismiss()
    }
    
    //加载OAuth页面
    func loadOAuthPage() {
        let urlStr = "https://api.weibo.com/oauth2/authorize?" + "client_id=" + client_id + "&redirect_uri=" + redirect_uri
        let url = NSURL(string: urlStr)
        let request = NSURLRequest(URL: url!)
        webView.loadRequest(request)
    }

}

//遵守webView协议,实现代理方法
extension OAuthViewController: UIWebViewDelegate {
    //webView开始加载的时候
    func webViewDidStartLoad(webView: UIWebView) {
        SVProgressHUD.show()
    }
    //webView加载完成时候
    func webViewDidFinishLoad(webView: UIWebView) {
        SVProgressHUD.dismiss()
    }
    //webView接收到请求的时候调用
    func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool {
        
        guard let urlStr = request.URL?.absoluteString else {
            return false
        }
        let codeFragment = "code="
        if urlStr.containsString(codeFragment) {
            guard let query = request.URL?.query else {
                return false
            }
            let code = (query as NSString).substringFromIndex(codeFragment.characters.count)
            loadAccessToken(code)
            
    }
    return true
    }
    
    
    func loadAccessToken(code: String) {
        //获取access_token
        UserAccountViewModel().getAccess_Token(code) { (isSuccess) -> () in
            if !isSuccess {
                print("登录失败")
                SVProgressHUD.showErrorWithStatus("登录失败")
                NSNotificationCenter.defaultCenter().postNotificationName(WeiBoSwitchRootController, object: nil)
                return
            }
            self.dismissViewControllerAnimated(false, completion: { () -> Void in
                NSNotificationCenter.defaultCenter().postNotificationName(WeiBoSwitchRootController, object: "Welcome")
                self.view.layoutIfNeeded()
            })
        }

        
        
    }
    
    /*
    //获取access_token
    func getAccess_Token(code: String) {
    let AFN = AFHTTPSessionManager()
    let urlStr = "https://api.weibo.com/oauth2/access_token"
    let params = ["client_id":client_id, "redirect_uri":redirect_uri, "grant_type":"authorization_code", "code":code, "client_secret":client_secret]
    //发送POST请求
    AFN.responseSerializer.acceptableContentTypes?.insert("text/plain")
    
    AFN.POST(urlStr, parameters: params, progress: nil, success: { (_, result) -> Void in
    let dict = result as! [String:AnyObject]
    let userAccount = UserAccount(dict: dict)
    //获取用户信息
    self.getUserInfo(userAccount)
    
    }) { (_, error) -> Void in
    print("error",error)
    }
    
    
    }
    
    //获取用户信息
    func getUserInfo(userAccount: UserAccount) {
    let AFN = AFHTTPSessionManager()
    let urlStr = "https://api.weibo.com/2/users/show.json"
    let params = ["access_token":userAccount.access_token!, "uid":userAccount.uid!]
    AFN.GET(urlStr, parameters: params, progress: nil, success: { (_, result) -> Void in
    let dict = result as! [String:AnyObject]
    userAccount.name = dict["name"] as? String
    userAccount.avatar_large = dict["avatar_large"] as? String
    userAccount.saveUserAccount()
    }) { (_, error) -> Void in
    print(error)
    }
    
    
    }

    */
    }